package com.yizisu.basemvvm.mvvm


import android.content.pm.PackageManager
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.yizisu.basemvvm.mvvm.mvvm_helper.*

/**
 * 若红楼梦空，亦初心不变
 * 作者：thinker
 * 包名：com.yizisu.basemvvm.mvvm
 * 时间：2019/3/27 11:05
 * 描述：
 * 强烈建议fragment不要使用带参数的构造函数
 * 比如旋转屏幕或者系统回收重建的时候会报错（could not find Fragment constructor）
 *
 */
abstract class MvvmFragment : Fragment(), BaseMvvmInterface {
    /**
     * 这个fragment是否对用户可见过
     */
    private var _isRunFirstVisible = false
    val isRunFirstVisible
        get() = _isRunFirstVisible
    /**
     * 动态权限请求码，随意
     */
    private val needPermissionCode = 1450
    /**
     * 动态权限的回调，是否有此权限
     */
    private var needPermissionCall: Function1<Boolean, Unit>? = null

    /**
     * viewModel
     */
    inline fun <reified M : MvvmViewModel> getActivityViewModel(): M? {
        val life = activity
        return if (life == null) null else ViewModelProvider(life).get(M::class.java)
    }

    /**
     * 获取依赖的fragment的viewModel
     */
    inline fun <reified M : MvvmViewModel> getParentFragmentViewModel(): M? {
        val life = parentFragment
        return if (life == null) null else ViewModelProvider(life).get(M::class.java)
    }


    val appCompatActivity: AppCompatActivity?
        get() = activity as? AppCompatActivity

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        initViewModel()
    }

    /**
     * 创建view
     */
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return when (val contentView = getLayoutResOrView(inflater)) {
            is Int -> {
                inflater.inflate(contentView, container, false)
            }
            is View -> {
                contentView
            }
            else -> {
                null
            }
        }
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initUi(savedInstanceState)
        getClickView()?.forEach {
            it?.setOnClickListener(this)
        }
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        initData()
        MessageBus.register(this)
    }

    override fun onDestroyView() {
        MessageBus.unRegister(this)
        super.onDestroyView()
    }

    /**
     * 通常和viewPager搭配
     */
    open fun getTitle(): CharSequence? {
        return null
    }

    /**
     * 请求用户权限
     */
    override fun getPermission(
        permission: MutableList<String>,
        needPermissionCall: Function1<Boolean, Unit>
    ) {
        if (context == null) {
            return
        }
        var isNeedRequest = false
        val list = mutableListOf<String>()
        permission.forEach {
            if (ActivityCompat.checkSelfPermission(
                    context!!,
                    it
                ) != PackageManager.PERMISSION_GRANTED
            ) {
                isNeedRequest = true
                list.add(it)
            }
        }
        if (isNeedRequest) {
            this.needPermissionCall = needPermissionCall
            if (list.isNotEmpty()) {
                requestPermissions(list.toTypedArray(), needPermissionCode)
            } else {
                needPermissionCall.invoke(true)
            }
        } else {
            needPermissionCall.invoke(true)
        }
    }

    override fun onResume() {
        if (!_isRunFirstVisible) {
            _isRunFirstVisible = true
            onFirstVisible()
        }
        super.onResume()
    }

    /**
     * 处理请求的权限结果
     */
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == needPermissionCode) {
            var isGetAllPermission = true
            grantResults.forEach {
                if (it != PackageManager.PERMISSION_GRANTED) {
                    isGetAllPermission = false
                }
            }
            needPermissionCall?.invoke(isGetAllPermission)
        }
    }
    /**
     * 注册livedata，忽略空的情况
     */
    inline fun <T> LiveBean<T>.register(crossinline observer: (LiveBean<T>) -> Unit): Observer<LiveBeanValue<T>> {
        return registerLiveBean(this@MvvmFragment, observer)
    }

    /**
     * 注册livedata，只处理成功的情况
     */
    inline fun <T> LiveBean<T>.registerOnSuccess(crossinline success: (T) -> Unit): Observer<LiveBeanValue<T>> {
        return registerOnSuccessLiveBean(this@MvvmFragment, success)
    }

    /**
     * 注册livedata，忽略空的情况
     */
    inline fun <T> MediatorLiveBean<T>.register(crossinline observer: (MediatorLiveBean<T>) -> Unit): Observer<LiveBeanValue<T>> {
        return registerLiveBean(this@MvvmFragment, observer)
    }

    /**
     * 注册livedata，只处理成功的情况
     */
    inline fun <T> MediatorLiveBean<T>.registerOnSuccess(crossinline success: (T) -> Unit): Observer<LiveBeanValue<T>> {
        return registerOnSuccessLiveBean(this@MvvmFragment, success)
    }

    /************************对于普通fragment下面是额外的功能***************************/

    /**
     * 创建其他格式的viewModel
     */
    inline fun <reified P : MvvmViewModel> getViewModel(): P {
        return ViewModelProvider(this).get(P::class.java)
    }

    /**
     * 当fragment第一次对用户展示的时候调用
     * 结合viewPage很好用
     */
    open fun onFirstVisible() {
    }
}